package com.seven.commons;

import lombok.extern.slf4j.Slf4j;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.lang.reflect.Method;
import java.util.Set;

/**
 * @author sevenDay
 * @classname ${CLASSNAME}
 * @description: 描述TODO
 * @date 2018/2/23
 */
@Slf4j
public class BeanValidatorUtils {

    private static final String VALUE_RESULT_TEMPLATE = ", 当前值为[%s]";

    private static  final  Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
    /**
     * 注意验证的对象的属性是对象类型，基本类型为包装类型的参数
     * @param object 针对bean参数
     * @param <T>
     */
    public static <T> String validate(T object,Class<?>[] group) {
        //执行验证
        Set<ConstraintViolation<T>> set = validator.validate(object);
        StringBuffer msg = new StringBuffer();
        String result="";
        for(ConstraintViolation<T> constraintViolation : set){
            result = constraintViolation.getMessage() + String.format(VALUE_RESULT_TEMPLATE, constraintViolation.getInvalidValue());
            break;
        }
        for(ConstraintViolation<T> constraintViolation : set){
            msg.append(constraintViolation.getPropertyPath() + " : " + constraintViolation.getMessage() + ",");
        }
        if(msg.length() > 0) {
            msg.deleteCharAt(msg.length()-1);
            log.info(""+msg.toString());
        }
        return result;
    }

    /**
     * 校验普通的参数方法和实现
     * @param obj
     * @param method
     * @param params
     * @param <T>
     * @return
     */
    private static  <T> Set<ConstraintViolation<T>> validMethodParams(T obj, Method method, Object[] params,Class<?>[] group) {

        return validator.forExecutables().validateParameters(obj, method, params,group);
    }
}
